/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.HashMap;
import java.util.Map;

import com.hiddenequity.adgroup_ad_service.AdGroupAdResponseParser;
import com.hiddenequity.adgroup_ad_service.AdGroupAdService;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.DataValidator;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

public class Act_AdOperation extends Act_Super{
	
	private String adGroupId;
	private String adId;
	private String campaignName;
	private String adGroupName;
	
	private EditText edit_ad_hedline;
	private EditText edit_ad_description1;
	private EditText edit_ad_description2;
	private EditText edit_ad_displayUrl;
	private EditText edit_ad_url;
	private Spinner spin_ad_UrlSchema;
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.super_operation_layout);
		
		((ViewStub) findViewById(R.id.stub_ad_operation)).inflate();
		
		Intent intent = getIntent();
		adGroupId = intent.getStringExtra("adGroupId");
		adId = intent.getStringExtra("adId");
        campaignName = intent.getStringExtra("campaignName");
        adGroupName = intent.getStringExtra("adGroupName");
        
        title.setText(getString(R.string.title_ad_add));
        sub_title.setText(campaignName + " / " + adGroupName);
		filter.setVisibility(View.GONE);
        
		edit_ad_hedline = (EditText) findViewById(R.id.edit_ad_hedline);
	    edit_ad_description1 = (EditText) findViewById(R.id.edit_ad_description1);
		edit_ad_description2 = (EditText) findViewById(R.id.edit_ad_description2);
		edit_ad_displayUrl = (EditText) findViewById(R.id.edit_ad_displayUrl);
		edit_ad_url = (EditText) findViewById(R.id.edit_ad_url);
		spin_ad_UrlSchema = (Spinner) findViewById(R.id.spin_ad_UrlSchema);
		
		Resources res = getResources();
		
        //populate url schema spinner
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item,
				res.getStringArray(R.array.arr_urlSchemas));
		
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		spin_ad_UrlSchema.setAdapter(adapter);
		
		//Get Ad data if id presented
		if(adId != null){
			title.setText(getString(R.string.title_ad_set));
			runOperationAsync(OPERATION_GET_DATA, getString(R.string.progress_loading), false);
		}
	}//onCreate
	
	
	
	/*
	 * Set Up Form
	 */
	private String initHeadline = "";
	private String initDescription1 = "";
	private String initDescription2 = "";
	private String initDisplayUrl = "";
	private String initUrl = "";
	
	private void setUpForm(){
		initHeadline = textAdData.get("headline");
		initDescription1 = textAdData.get("description1");
		initDescription2 = textAdData.get("description2");
		initDisplayUrl = textAdData.get("displayUrl");
		initUrl = textAdData.get("url");
		
		edit_ad_hedline.setText(initHeadline);
		edit_ad_description1.setText(initDescription1);
		edit_ad_description2.setText(initDescription2);
		edit_ad_displayUrl.setText(initDisplayUrl);

		if(initUrl.contains("http://")){
			edit_ad_url.setText(initUrl.replace("http://", ""));
			spin_ad_UrlSchema.setSelection(0);
		} else {
			edit_ad_url.setText(initUrl.replace("https://", ""));
			spin_ad_UrlSchema.setSelection(1);
		}
	}//setUpForm
	
	
		
	/*
	 * Get ad list
	 */
	Map<String, String> textAdData = new HashMap<String, String>();
	private void getTextAd(){
		textAdData.clear();

		AdGroupAdResponseParser parser = new AdGroupAdResponseParser(
				Communication.postSOAP(AdGroupAdService.URL_ADGROUP_AD_SERVICE,
						AdGroupAdService.getTextAdById(adId)));
		
		responseErrorString = parser.checkForErrors();
		
		textAdData.putAll(parser.getAdData());	
	}//getAdById
	
		
	
	/*
	 * Set or add ad, depends on Ad id provided
	 */
	public void onClick_saveData(View v){
    	if(isDataValid()){
        	runOperationAsync(OPERATION_SET_DATA, getString(R.string.progress_saving), false); 		
    	} else {
    		showOperationError(R.string.msg_title_invalid_data, formErrorString);
    	}
	}//onClick_setAd
	
	
	
	/*
	 * Set or add ad, depends on Ad id provided
	 */
	private boolean isChangesMade = true;
	private void textAdAddOperation(){

		if(initHeadline.equals(headline) && initDescription1.equals(description1) &&
				initDescription2.equals(description2) && initDisplayUrl.equals(displayUrl) &&
				initUrl.equals(url)){
			
			isChangesMade = false;
			return;
		}
		
		AdGroupAdResponseParser parser = new AdGroupAdResponseParser(
				Communication.postSOAP(AdGroupAdService.URL_ADGROUP_AD_SERVICE,
				AdGroupAdService.textAdAddOperation(adGroupId, headline, description1, 
						description2, displayUrl, url)));
		responseErrorString = parser.checkForErrors();			
	}//textAdAddOperation
	

	/*
	 * Remove TextAd Operation
	 */
	protected void textAdRemoveOperation() {
		
		if(adId == null || !isChangesMade)
			return;
		
		AdGroupAdResponseParser parser = new AdGroupAdResponseParser(
				Communication.postSOAP(AdGroupAdService.URL_ADGROUP_AD_SERVICE,
				AdGroupAdService.textAdRemoveOperation(adGroupId, adId)));
		
		responseErrorString = parser.checkForErrors();			
	}//textAdRemoveOperation
	
	
	/*
	 * Validating dada
	 */
	private String headline;
	private String description1;
	private String description2;
	private String displayUrl;
	private String url;
	
	private boolean isDataValid(){
		boolean result = true;
		
		headline = edit_ad_hedline.getText().toString();
		description1 = edit_ad_description1.getText().toString();
		description2 = edit_ad_description2.getText().toString();
		displayUrl = edit_ad_displayUrl.getText().toString();
		
		String urlSchema = spin_ad_UrlSchema.getItemAtPosition(
				spin_ad_UrlSchema.getSelectedItemPosition()).toString();
		url = edit_ad_url.getText().toString();
		if(!url.equals(""))
			url = urlSchema + url;	
		
		if(!DataValidator.isName(headline)){
			formErrorString = getString(R.string.msg_invalid_textad_headline);
			edit_ad_hedline.requestFocus();
			result = false;
		} else if(!DataValidator.isAdText(description1)){
			formErrorString = getString(R.string.msg_invalid_textad_description1);
			edit_ad_description1.requestFocus();
			result = false;
		} else if(!DataValidator.isAdText(description2)){
			formErrorString = getString(R.string.msg_invalid_textad_description2);
			edit_ad_description2.requestFocus();
			result = false;
		} else if(!DataValidator.isUrl(displayUrl, false, false)){
			formErrorString = getString(R.string.msg_invalid_textad_displayurl);
			edit_ad_displayUrl.requestFocus();
			result = false;
		} else if(!DataValidator.isUrl(url, true, false)){
			formErrorString = getString(R.string.msg_invalid_target_url);
			edit_ad_url.requestFocus();
			result = false;
		}

		return result;
	}
	

	
    /*
     * Async operations
     */
	private void runOperationAsync(final int operation, String message, boolean overlap) {
		// Stop if thread is alive
		if (thread.isAlive() && !overlap)
			return;

		// Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		// Check if Internet connection alive
		if (!isConnectionAvalable()) {
			progressDialog.dismiss();
			return;
		}

		thread = new Thread() {
			public void run() {
				// Perform authentication
				new AuthService(Act_AdOperation.this, getApplication());

				// Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
						case OPERATION_GET_DATA:
							Act_AdOperation.this.getTextAd();
							break;
						case OPERATION_SET_DATA:
							Act_AdOperation.this.textAdAddOperation();
							break;
						case OPERATION_REMOVE_DATA:
							Act_AdOperation.this.textAdRemoveOperation();
							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// Perform postoperation
				Act_AdOperation.this.runOnUiThread(new Runnable() {
					public void run() {

						progressDialog.dismiss();

						if (AuthService.authToken != null) {

							showOperationError(R.string.msg_title_error,
									responseErrorString);

							switch (operation) {

							case OPERATION_GET_DATA:
								setUpForm();
								break;

							case OPERATION_SET_DATA:
								if (responseErrorString == null)
									runOperationAsync(
											OPERATION_REMOVE_DATA,
											getString(R.string.progress_removing),
											true);
								break;

							case OPERATION_REMOVE_DATA:
								if (responseErrorString == null)
									if (isChangesMade) {
										finishActivityWithResult(RESPONSE_REFRESH_REQUIRED);
									} else {
										finishActivityWithResult(RESPONSE_NO_REFRESH_REQUIRED);
									}
								break;
							}

						} else {
							Intent intent = new Intent(Act_AdOperation.this
									.getApplicationContext(), Act_Login.class);
							startActivityForResult(intent,
									REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start();
	}//runOperationAsync
}
